#!/usr/bin/python
#-*- coding:utf-8 -*-


import sys

import time
import requests
import os
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from utils.custom_log import log_start
logger = log_start('check_URL')


def verify_url(url):
    try:
        request = requests.get(url,timeout=10,allow_redirects=False)
        httpStatusCode = request.status_code
        if httpStatusCode <= 302: # 重定向301,302
            ret = '接口测试:\033[32m %s  返回状态:[%s]\033[0m ' %(url,httpStatusCode)
        else:
            ret = '接口测试:\033[32m %s  返回状态:\033[0m\033[31m[%s] \033[0m' %(url,httpStatusCode)
       
        logger.info(ret)
        return True
    
    except requests.exceptions.ConnectionError:
        info = "Connection refused  sleep 10s ........ {}".format(url)
        logger.error(info)
        time.sleep (10)
    except requests.exceptions.ReadTimeou:
        info = "Connection readTime ........ {}".format(url)
        logger.error(info)
    except requests.exceptions.ConnectTimeout:
        info = "Connection timeout ........ {}".format(url)
        logger.error(info)
    except requests.exceptions.HTTPError as e:
        return e

def getHttpStatus(url):
    for i in range(5):
        try:
            if verify_url(url):
                return True
            else:
                continue
        except KeyError:
            continue


if __name__ == "__main__":
    # url="https://www.szccpx.com"
    url="https://opsbase.cn"
    getHttpStatus(url)